<?php
namespace app\api\controller;

use Lib\Conf;
use lib\Db;
use lib\Cache;
use lib\Response;

class User extends Common {

    /**
     * 获取用户详情
     * @return array
     */
    function info(){
        $info = Db::name('user u')->join('user_info i', 'u.id = i.uid', 'left')
            ->where(['uid'=>$this->uid])->select();
        return Response::success('ok', $info);
    }

    /**
     * 小程序自动登陆
     * @return array
     */
    function miniReg(){
        if(empty($this->request->post['code'])){
            return Response::error('获取登陆码失败!');
        }
        $result = json_decode($this->request->create('https://api.weixin.qq.com/sns/jscode2session', array(
            'appid' => Conf::get('appId'),
            'secret' => Conf::get('appSecret'),
            'js_code'   => $this->request->post['code'],
            'grant_type'    => 'authorization_code',
        )), true);
        if($result['openid']){
            $userId = $this->createUser($result['openid']);
            $token = $this->createToken($userId);
            return Response::success('ok', array('token'=>$token));
        }else{
            return Response::error('获取OPENID失败!');
        }
    }

    /**
     * 创建用户
     * @param $openid
     * @return array|bool|\mysqli_result
     */
    protected function createUser($openid){
        Db::transaction();
        try{
            $userId = Db::name('user')->insert(array(
                'openid'    => $openid,
                'avatar'    => $this->request->post['pic'],
                'nickname'    => $this->request->post['name'],
            ), true);
            Db::name('user_info')->insert(array(
                'uid'   => $userId,
                'time'  => time()
            ));
            Db::commit();
            return $userId;
        }catch (\Exception $e){
            return Response::error($e->getMessage());
        }
    }

    /**
     * 创建用户
     * @param $uid
     * @return string
     */
    protected function createToken($uid){
        $token = md5(uniqid($this->tokenPrefix, true) . $uid);
        Cache::Set("{$this->tokenPrefix}_{$token}", $uid, 3 * 86400);
        return $token;
    }

}